package cn.sell.mbg.sys.relation.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.sell.comm.base.MySqlCrudServiceImpl;
import cn.sell.mbg.sys.menu.UmsMenu;
import cn.sell.mbg.sys.menu.mapper.UmsMenuMapper;
import cn.sell.mbg.sys.relation.UmsRoleMenuRelation;
import cn.sell.mbg.sys.relation.mapper.UmsRoleMenuRelationMapper;
import cn.sell.mbg.sys.relation.service.UmsRoleMenuRelationService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
@Transactional
public class UmsRoleMenuRelationServiceImpl
        extends MySqlCrudServiceImpl<UmsRoleMenuRelation, Long>
        implements UmsRoleMenuRelationService {

    @Autowired
    private UmsMenuMapper umsMenuMapper;

    @Autowired
    private UmsRoleMenuRelationMapper umsRoleMenuRelationMapper;
    //输入用户id返回给前端menu

    public List<UmsMenu> getCheckedMenu(Long roleId) {
        List<UmsMenu> umsMenuList = new ArrayList<UmsMenu>();
        UmsRoleMenuRelation roleMenuRelation = new UmsRoleMenuRelation();
        roleMenuRelation.setRoleId(roleId);
        List<UmsRoleMenuRelation> roleMenuRelationList = umsRoleMenuRelationMapper.select(roleMenuRelation);
        for (UmsRoleMenuRelation umsRoleMenuRelation : roleMenuRelationList) {
            UmsMenu umsMenu = umsMenuMapper.selectByPrimaryKey(umsRoleMenuRelation.getMenuId());
            umsMenuList.add(umsMenu);
        }
        return umsMenuList;
    }

    /**
     * 更新
     */
    public Long saveOrUpdateChecked(Long roleId, String menuIds) {

        Long count = 0l;
        UmsRoleMenuRelation umsRoleMenuRelation = new UmsRoleMenuRelation();
        umsRoleMenuRelation.setRoleId(roleId);
        umsRoleMenuRelationMapper.delete(umsRoleMenuRelation);

        String[] splits = menuIds.split(",");
        for (String s : splits) {
            if (StrUtil.isNotEmpty(s)) {
                long menuId = Long.valueOf(s).longValue();
                UmsRoleMenuRelation roleMenuRelation = new UmsRoleMenuRelation();
                roleMenuRelation.setMenuId(menuId);
                roleMenuRelation.setRoleId(roleId);
                count = count + umsRoleMenuRelationMapper.insert(roleMenuRelation);
            }
        }
        return count;
    }

    public int deleteByRoleId(Long roleId) {
        UmsRoleMenuRelation umsRoleMenuRelation = new UmsRoleMenuRelation();
        umsRoleMenuRelation.setRoleId(roleId);
        return umsRoleMenuRelationMapper.delete(umsRoleMenuRelation);
    }

}
